package com.kvest.mobile_newspaper.activities;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Stack;

import com.kvest.mobile_newspaper.R;
import com.kvest.mobile_newspaper.android.ClubListAdapter;
import com.kvest.mobile_newspaper.core.ClubsWrapper;
import com.kvest.mobile_newspaper.datamodel.*;
import com.kvest.mobile_newspaper.network.GetClubRequest;
import com.kvest.mobile_newspaper.network.GetClubRequest.GetClubResult;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

Проверить почему в статье нет данных(вывести в Логкэт)
Добавить keepScreenOn на все активити
Добавить логирование

public class ClubViewActivity extends NewspaperBaseActivity 
{
    private static final long DELTA_TIME = 1262304000000L;
	//dialogs
	private static final int ACTION_DIALOG_ID = 1;
	private static final int DELETE_CONFIRMATION_DIALOG_ID = 2;
	public static final int UPDATE_OK_DIALOG_ID = 3;
    public static final int UPDATE_SOME_ERROR_DIALOG_ID = 4;
    public static final int UPDATE_FATAL_ERROR_DIALOG_ID = 5;
		
	public static final String CLUB_ID = "club_id";
	
	public static final String CLUB_LIST_TYPE = "club_list_type";
	public static final String PATH_IDS = "path_ids";
	
	private enum ClubsListType 
	{
		cltAllArticles, cltByCategories;
	};
	
	private ElementsContainer club;
	private Element selectedElement;
	
	private ClubListAdapter adapter;
	private ArrayList<Element> shownElements;
	private ClubsListType clubsListType;
	private Stack<ElementsContainer> path;
	
	private GetClubRequest clubRequest = null;
	private Handler guiHandler;
	private ProgressDialog progressDialog = null;

    private SimpleDateFormat simpleDateFormat;
	
	@Override
    public void onCreate(Bundle savedInstanceState) 
	{
        super.onCreate(savedInstanceState);
        setContentView(R.layout.club_view);

        guiHandler = new Handler();

        simpleDateFormat = new SimpleDateFormat("dd.MM.yyyy");

        clubsListType = ClubsListType.cltAllArticles;
        path = new Stack<ElementsContainer>();
        
        club = ClubsWrapper.getWrapper().getElementsContainer(getIntent().getExtras().getString(CLUB_ID));  
        setTitle(club != null ? club.getName() : ""); 
        
        //���������� ����������� ��������
        initializeAdapter();
        initializeContentList();  
        
        //��������������� ���������
        if (getLastNonConfigurationInstance() != null)
        {
        	restoreSavedData((SavedData)getLastNonConfigurationInstance());
        }
        
        //������������� ������� ��� �����������
        setContentList();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		super.onCreateOptionsMenu(menu);
		
		getMenuInflater().inflate(R.menu.club_view_menu, menu);
		
		return true;
	}

	@Override 
	public boolean onPrepareOptionsMenu (Menu menu)
	{
		super.onPrepareOptionsMenu(menu);
		
		return (clubsListType == ClubsListType.cltAllArticles);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{
		if (item.getItemId() == R.id.menu_by_categories)
		{
			clubsListType = ClubsListType.cltByCategories;
			setContentList();
   		
			return true;
		}

   		return super.onOptionsItemSelected(item);    	
	}
	
	@Override
    public void onStop()
    {
    	//�������� �������
    	if (clubRequest != null)
    	{
    		clubRequest.interrupt();
    	}
    	
    	//������� ���������� ���� ��������
    	if (progressDialog != null)
    	{
    		progressDialog.dismiss();
    	}
    	
    	super.onStop();
    }
	
	@Override
	public void onBackPressed() 
	{
		if (path.isEmpty())
		{
			super.onBackPressed();
		}
		else
		{
			path.pop();
			setContentList();
		}
	}	
	
	@Override
	public Object onRetainNonConfigurationInstance() 
	{
		return new SavedData(clubsListType, path);
	}
	
	@Override
    protected Dialog onCreateDialog(int id) 
    {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		
        switch (id) 
        {
        	case ACTION_DIALOG_ID : 
        		builder.setTitle(R.string.action);
        		builder.setItems(new String []{getString(R.string.update), getString(R.string.delete)}, new OnClickListener() 
        		{	
					public void onClick(DialogInterface dialog, int which) 
					{
						//���������� ����� �������
						switch (which) 
						{
							case 0 : updateSelectedElement(); break;
							case 1 : showDeleteConfirmationDialog(); break;
						}
						
						dialog.dismiss();
						
					}
				});
        	    break;
        	case DELETE_CONFIRMATION_DIALOG_ID : 
        		builder.setTitle(R.string.confirmation);
        		builder.setIcon(android.R.drawable.ic_dialog_alert);
        		builder.setMessage(""); 
        		builder.setNegativeButton(android.R.string.no, null);
        		builder.setPositiveButton(android.R.string.yes,  new DialogInterface.OnClickListener() 
    	    	{	
    				public void onClick(DialogInterface dialog, int which) 
    				{
    					deleteSelectedElement();
    				}
    	    	});
        		break;
        	case UPDATE_FATAL_ERROR_DIALOG_ID :
        		builder.setTitle(R.string.error);
        		builder.setIcon(android.R.drawable.ic_dialog_alert);
        		builder.setMessage(R.string.load_error);
        		builder.setPositiveButton(android.R.string.ok,null);
        		break;
        	case UPDATE_SOME_ERROR_DIALOG_ID :
        		builder.setIcon(android.R.drawable.ic_dialog_alert);
        		builder.setMessage(R.string.load_with_error);
        		builder.setPositiveButton(android.R.string.ok,null);
        		break;	
        	case UPDATE_OK_DIALOG_ID :
        		builder.setIcon(android.R.drawable.ic_dialog_info);
        		builder.setMessage(R.string.load_ok);
        		builder.setPositiveButton(android.R.string.ok,null);
        		break;	
        }
        
        return builder.create();
    }
	
	@Override
    protected void onPrepareDialog(int id, Dialog dialog) 
    {
		if (id == DELETE_CONFIRMATION_DIALOG_ID)
		{
			((TextView)dialog.findViewById(android.R.id.message)).setText(String.format(getResources().getString(R.string.delete_confirmation_text), selectedElement.getName()));
		}
    }
	
	private void restoreSavedData(SavedData savedData)
	{
		clubsListType = savedData.getClubsListType();
		path.clear();
		path.addAll(savedData.getPath());
	}
	
	private void initializeAdapter()
	{
		shownElements = new ArrayList<Element>();
		adapter = new ClubListAdapter(getApplicationContext(), R.layout.club_list_item, shownElements);
		adapter.setaAtionsListener(new ClubListAdapter.ActionsListener() 
		{
			public void elementAction(Element element) 
			{
				//���������� ��������� �������
				selectedElement = element;
				
				if (selectedElement instanceof Article || selectedElement instanceof ProxyArticle)
				{
					showDialog(DELETE_CONFIRMATION_DIALOG_ID);
				}
				else
				{
					//���������� ������ ������ ��������
					showDialog(ACTION_DIALOG_ID);
				}
			}
		});
	}
	
	private void initializeContentList()
    {
    	ListView contentList = (ListView)findViewById(R.id.club_view_list);
		contentList.setAdapter(adapter);
		
		contentList.setOnItemClickListener(new AdapterView.OnItemClickListener() 
        {
	        public void onItemClick(AdapterView<?> parent, View itemClicked, int position, long id) 
	        {	
	        	Element selectedItem = shownElements.get(position);
                if (selectedItem instanceof DateElement) {
                    return;
                }

	        	showSelectedItem(selectedItem);
	        }
        });
	}
    
    private void setContentList()
    {
    	shownElements.clear();

    	if (clubsListType == ClubsListType.cltAllArticles)
    	{
    		club.getAllArticles(shownElements);
    	}
    	else if (clubsListType == ClubsListType.cltByCategories)
    	{
    		ElementsContainer currentContainer;
    		if (path.isEmpty())
    		{
    			currentContainer = club;
    		}
    		else
    		{
    			currentContainer = path.lastElement();
    		}
    		
    		for (int i = 0; i < currentContainer.getChildrenCount(); ++i)
    		{
    			shownElements.add(currentContainer.getChild(i));
    		}
    	}

        String previousDate = "";
        Element element;
        for (int i = 0; i < shownElements.size(); ++i) {
            element = shownElements.get(i);
            if (element instanceof ProxyArticle) {
                String nextDate = simpleDateFormat.format(new Date(((ProxyArticle)element).getDate() * 1000L + DELTA_TIME));
                if (!previousDate.equals(nextDate)) {
                    shownElements.add(i, new DateElement(nextDate));
                    previousDate = nextDate;
                    ++i;
                }
            } else if (element instanceof Article) {
                String nextDate = simpleDateFormat.format(new Date(((Article)element).getDateAsLong() * 1000L + DELTA_TIME));
                if (!previousDate.equals(nextDate)) {
                    shownElements.add(i, new DateElement(nextDate));
                    previousDate = nextDate;
                    ++i;
                }
            }
        }

        guiHandler.post(new Runnable() {
            public void run() {
                adapter.notifyDataSetChanged();
            }
        });
    }
    
    private void showSelectedItem(Element selectedItem)
    {
    	if ((selectedItem instanceof Article) || (selectedItem instanceof ProxyArticle))
    	{
    		Intent intent = new Intent(this, ArticleActivity.class);
        	intent.putExtra(BaseArticleActivity.ARTICLE_ID, selectedItem.getId()); 
    	    startActivity(intent);
    	}
    	else if (selectedItem instanceof ElementsContainer)
    	{
    		path.push((ElementsContainer)selectedItem);
    		setContentList();
    	}
    }
    
    private void showDeleteConfirmationDialog()
    {
    	if (selectedElement != null)
    	{
    		showDialog(DELETE_CONFIRMATION_DIALOG_ID);
    	}
    }
    
    private void updateSelectedElement()
    {
    	if (selectedElement != null)
    	{
    		update();
    	}
    }
    
    private void deleteSelectedElement()
    {
	    if (selectedElement != null)
		{
	    	ClubsWrapper.getWrapper().deleteElement(selectedElement);
	    	
	    	//update shown data
	    	setContentList();
		}
    }
    
    private class SavedData
    {
    	private ClubsListType clubsListType;
    	private Stack<ElementsContainer> path;
    	
    	public SavedData(ClubsListType clubsListType, Stack<ElementsContainer> path)
    	{
    		this.clubsListType = clubsListType;
    		this.path = new Stack<ElementsContainer>(); 
    		this.path.addAll(path);
    	}

		public ClubsListType getClubsListType() 
		{
			return clubsListType;
		}

		public Stack<ElementsContainer> getPath() 
		{
			return path;
		}
    }
    
    private void update()
    {
    	//���������� ������ ��������
    	showProgressDialog(true);
    	
    	clubRequest = new GetClubRequest(selectedElement.getRoot().getId(), selectedElement.getId(), new GetClubRequest.GetClubResult() 
    	{
			public void clubResult(int resultType, ElementsContainer club, String clubParentId) 
			{				
				if (resultType == GetClubResult.OK_RESULT || resultType == GetClubResult.SOME_ERROR_RESULT)
				{
					 if (club != null)
			         {
						 //��������
						 ClubsWrapper.getWrapper().replaceCategory(clubParentId, club);
						 
						 //���������
						 ClubsWrapper.getWrapper().save();
						 
						 //��������� �������
						 setContentList();
			         }
				}

				//���������� ��������� ��������
				showUpdateResult(resultType);
				
				clubRequest = null;
			}

		});
    	clubRequest.sendRequest();
    }
    
    private void showUpdateResult(final int resultType)
    {
    	guiHandler.post(new Runnable() 
		{	
			public void run() 
			{
		        //������� ����� ��������
		        progressDialog.dismiss();
		        
		        //���������� ��������� �� ��������� ��������
		        switch (resultType) 
		        {
					case  GetClubResult.OK_RESULT: showDialog(UPDATE_OK_DIALOG_ID); break;
					case  GetClubResult.SOME_ERROR_RESULT: showDialog(UPDATE_SOME_ERROR_DIALOG_ID); break;
					case  GetClubResult.FATAL_ERROR_RESULT: showDialog(UPDATE_FATAL_ERROR_DIALOG_ID); break;
				}
			}
		});
    }
    
    //����� ���������� ������ ��������
    private void showProgressDialog(boolean isLoadFromNet)
    {
    	progressDialog = ProgressDialog.show(
    			ClubViewActivity.this,
    			getResources().getString(R.string.loading),
    			getResources().getString(isLoadFromNet ? R.string.loading_text :  R.string.file_loading_text),
    			true);
    	
    	TextView text = (TextView)progressDialog.findViewById(android.R.id.message);
    	if (text != null)
    	{
    		text.setTextColor(getResources().getColor(R.color.title_text_color));
    	}
    }
}
